import { useRef, useImperativeHandle } from 'react'
import { useNavigate } from 'react-router-dom'
import Copy from '$tp/copy'
/* -------------------------------------------------------- Declare -- */
const { $lazy, $ } = window
/* -------------------------------------------------------- Async Component -- */
import ModTableName from './_config/mod-table-name'
import ModMigration from '../../_config/mod-migration'
import ModModel from '../../_config/mod-model'
const SearchTable = $lazy.hook(()=>import('#cpt/temp/SearchTable'))
const className = 'nosel cp abs_full fxm pl5'
/* -------------------------------------------------------- Page Component -- */
const Component = ({ dbRef, database, folder, onEntity }, ref) => {
	const tableRef = useRef()
	const navigate = useNavigate()
	const onceRef = useRef()
	useImperativeHandle( ref, () => tableRef )
	const onOk = () => {
		$.ref($.ref(dbRef)).tableRef().refresh()
	}
	const onRefresh = () => {
		$.ref($.ref(dbRef)).tableRef().refresh()
		$.ref($.ref(tableRef)).tableRef().refresh()
	}
	const config = {
		page : {
			title: { title:'表记录', titleMode:2 },
			minWidth: 600,
			controls	: [
				{ mode:'del', onOk, abs:0, way:'post', param:{ database } }
			]
		},
		// 搜索配置
		search : {
			query 		: { database },
			data:[
				{ label:'表名称', 	name:'table_name' },
			],
		},
		// 表格配置
		table: {
			api 		: 'mysql/seaql_migrations',				// 列表、增、删，改、查五合一接口
			delApi 		: 'mysql/seaql_migrations/del',
			paging 		: 0,					// 接口是否分页
			idStr 		: 'version',
			max 		: 1000,
			row:{},
			cols		: [
				{ title: '表', 			dataIndex: 'version', width:200, sorter:1, render: t => {
					return (
						<div className={className} onClick={e=>e.stopPropagation()}>
							<div className='ex' onClick={()=>{$.pushNext(navigate, '/structure', { t })}}><b className='ar f13'>{t}</b></div>
							<Copy t={t}/>
						</div>
					)
				}},
			],
			controls 	: {
				width 	: 220,
				data: ({ version, top }) => [
					{ mode:'delPop', label:'删除', onOk, abs:0, way:'post', param:{ id:version, database } },
					{ mode:'submit', api:'mysql/seaql_migrations/top', label: top ? '取顶' : '置顶', gray:!top, abs:0, r:1, way:'put', param:{ table_name:version, database, top: !top } },
					{ label:'修改', mode: 'formModal', hide: !/^m\d/.test(version), r:1, config:ModTableName({ table_name:version, database }) },
					{ label:'Migration', mode: 'formModal',  config: ModMigration({ table_name:version, folder, onRefresh }) },
					{ label:'Model', mode: 'formModal',  config:ModModel({table_name:version, folder, onEntity}) }
				]
			},
			onOk: (_, { param }) => {
				if( onceRef.current === 1 ) $.ref($.ref(dbRef)).tableRef().search({ param })
				if( !onceRef.current ) onceRef.current = 1
			}
		}
	}
	return <SearchTable ref={tableRef} {...config}/>
}
export default Component